#!/usr/bin/python
# -*- coding: utf-8 -*-
# @File : coroutine_utilss
# @Time : 2023/10/9 10:52
# @Author : yu.qian
"""
 ____    _____    ____   _                       _   ____     ___    ____    ____  
|  _ \  |_   _|  / ___| | |   ___    _   _    __| | |___ \   / _ \  |___ \  | ___| 
| | | |   | |   | |     | |  / _ \  | | | |  / _` |   __) | | | | |   __) | |___ \ 
| |_| |   | |   | |___  | | | (_) | | |_| | | (_| |  / __/  | |_| |  / __/   ___) |
|____/    |_|    \____| |_|  \___/   \__,_|  \__,_| |_____|  \___/  |_____| |____/ 
                                                                                   
"""

import asyncio
from functools import wraps

is_coroutine = asyncio.iscoroutinefunction


def to_sync(func):
    if not is_coroutine(func):
        return func

    @wraps(func)
    def wrapper(*args, **kwargs):
        # 获取的是当前线程的事件循环
        loop = asyncio.get_event_loop()
        # 将协程函数包装成任务
        fut = asyncio.ensure_future(func(*args, **kwargs))
        # 将任务注册到事件循环中并启动事件循环
        loop.run_until_complete(asyncio.gather(fut))
        # 返回任务的结果
        return fut.result()
    return wrapper


# if __name__ == '__main__':
#     @to_sync
#     async def test():
#         await asyncio.sleep(0.01)
#         return 1
#     print(test())
#
#     to_sync(test)()